package com.jfl.core.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.jfl.core.shiro.CustomRealm;
import com.jfl.model.SysUser;

/**
 * web模块单独工具类
 * 
 * @author 赵炎
 * @version [V1.00, 2018年12月14日]
 * @since V1.00
 */
public class ShiroUtils
{
    /**
     * 保存用户信息
     * 只是用户更新shiro中个人信息，不是对权限操作
     * 
     * @param user
     */
    public static void setCurrentUser(SysUser user)
    {
        Subject subject = ShiroUtils.getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        subject.runAs(newPrincipalCollection);
    }
    
    /**
     * 获取当前用户对象
     * 集成热部署存在无法转型的错误 需要去除热部署的jar包
     * 
     * @return
     */
    public static SysUser getCurrentUser()
    {
        return (SysUser)SecurityUtils.getSubject().getPrincipal();
    }
    
    /**
     * 清除shiro缓存
     */
    public static void clearCachedAuthorizationInfo()
    {
        RealmSecurityManager rsm = (RealmSecurityManager)SecurityUtils.getSecurityManager();
        CustomRealm realm = (CustomRealm)rsm.getRealms().iterator().next();
        realm.clearCachedAuthorizationInfo();
    }
    
    /**
     * 获取登录用户Id
     * 
     * @return
     */
    public static Long getCurrentUserId()
    {
        return ShiroUtils.getCurrentUser().getId();
    }
    
    /**
     * 主题
     * 
     * @return
     */
    public static Subject getSubject()
    {
        return SecurityUtils.getSubject();
    }
    
    /** 
     * 会话对象
     * @return
     */
    public static Session getSession()
    {
        return ShiroUtils.getSubject().getSession();
    }
    
    public static void logout()
    {
        // 删除缓存
        Subject subject = ShiroUtils.getSubject();
        RealmSecurityManager rsm = (RealmSecurityManager)SecurityUtils.getSecurityManager();
        CustomRealm realm = (CustomRealm)rsm.getRealms().iterator().next();
        realm.deleteSession((String)subject.getSession().getId());
        subject.logout();
    }
    
    /** 
     * 获取主机地址
     * @return
     */
    public static String getIp()
    {
        return ShiroUtils.getSession().getHost();
    }
}
